<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>无障碍阅读助手</title>
    <script src="https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/pdf.js@3.11.174/build/pdf.min.js"></script>
    <style>
        :root {
            --primary-color: #4a90e2;
            --text-color: #333;
            --bg-color: #fff;
            --contrast-high: #000;
            --contrast-low: #fff;
            --font-size: 16px;
        }

        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: var(--text-color);
            background-color: var(--bg-color);
            margin: 0;
            padding: 20px;
            max-width: 1000px;
            margin: 0 auto;
        }

        .container {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        h1 {
            color: var(--primary-color);
            text-align: center;
        }

        .upload-section {
            border: 2px dashed #ccc;
            padding: 20px;
            text-align: center;
            border-radius: 8px;
            background-color: #f9f9f9;
        }

        .upload-section:hover {
            border-color: var(--primary-color);
        }

        .controls {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
        }

        .control-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        button {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #357abd;
        }

        .share-button {
            background-color: #28a745;
        }

        .share-button:hover {
            background-color: #218838;
        }

        .result-section {
            border: 1px solid #ddd;
            padding: 20px;
            border-radius: 8px;
            min-height: 200px;
            font-size: var(--font-size);
            background-color: var(--bg-color);
            color: var(--text-color);
        }

        .loading {
            display: none;
            text-align: center;
            margin: 20px 0;
        }

        .loading-spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid var(--primary-color);
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .preview-image {
            max-width: 100%;
            max-height: 300px;
            margin-top: 10px;
            display: none;
        }
        
        input[type="url"] {
            width: 70%;
            padding: 8px;
            margin-right: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        .status {
            margin-top: 10px;
            font-style: italic;
            color: #666;
        }

        /* 响应式设计 */
        @media (max-width: 600px) {
            .controls {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>无障碍阅读助手</h1>
        
        <div class="upload-section">
            <h2>上传图片或PDF文件</h2>
            <input type="file" id="fileInput" accept="image/*,.pdf" />
            <p>支持格式：JPG, PNG, GIF, BMP, PDF</p>
            <img id="previewImage" class="preview-image" alt="预览图" />
        </div>
        
        <div class="upload-section">
            <h2>解析网页内容</h2>
            <input type="url" id="urlInput" placeholder="输入网页URL" />
            <button id="parseUrlButton">解析网页</button>
            <p>直接解析网页中的文本内容</p>
        </div>

        <div class="loading">
            <div class="loading-spinner"></div>
            <p id="progressStatus">正在处理...</p>
        </div>

        <div class="controls">
            <div class="control-group">
                <label for="fontSize">字体大小:</label>
                <input type="range" id="fontSize" min="16" max="72" value="24" />
                <span id="fontSizeValue">24px</span>
            </div>
            
            <div class="control-group">
                <label for="contrast">对比度:</label>
                <select id="contrast">
                    <option value="normal">正常</option>
                    <option value="high">高对比度 (黑底白字)</option>
                    <option value="yellow">黄底黑字</option>
                </select>
            </div>
            
            <button id="readButton" disabled>朗读文本</button>
            <button id="pauseButton" disabled>暂停朗读</button>
            <button id="shareButton" class="share-button" disabled>快速分享给视障朋友</button>
        </div>

        <div class="result-section" id="resultText"></div>
        
        <div class="status" id="status"></div>
    </div>

    <script>
        // 全局变量
        let recognizedText = '';
        let isReading = false;
        let utterance = null;
        
        // DOM 元素
        const fileInput = document.getElementById('fileInput');
        const previewImage = document.getElementById('previewImage');
        const resultText = document.getElementById('resultText');
        const readButton = document.getElementById('readButton');
        const pauseButton = document.getElementById('pauseButton');
        const shareButton = document.getElementById('shareButton');
        const fontSizeSlider = document.getElementById('fontSize');
        const fontSizeValue = document.getElementById('fontSizeValue');
        const contrastSelect = document.getElementById('contrast');
        const loadingElement = document.querySelector('.loading');
        const progressStatus = document.getElementById('progressStatus');
        const statusElement = document.getElementById('status');

        // 初始化 PDF.js
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.jsdelivr.net/npm/pdf.js@3.11.174/build/pdf.worker.min.js';

        // 事件监听器
        fileInput.addEventListener('change', handleFileUpload);
        document.getElementById('parseUrlButton').addEventListener('click', parseWebContent);
        fontSizeSlider.addEventListener('input', updateFontSize);
        contrastSelect.addEventListener('change', updateContrast);
        readButton.addEventListener('click', startReading);
        pauseButton.addEventListener('click', togglePauseReading);
        shareButton.addEventListener('click', shareContent);

        // 文件上传处理
        async function handleFileUpload(event) {
            const file = event.target.files[0];
            if (!file) return;

            // 重置状态
            recognizedText = '';
            resultText.textContent = '';
            readButton.disabled = true;
            pauseButton.disabled = true;
            shareButton.disabled = true;
            
            // 显示加载状态
            loadingElement.style.display = 'block';
            progressStatus.textContent = '正在处理...';

            try {
                if (file.type.startsWith('image/')) {
                    // 处理图片
                    await processImage(file);
                } else if (file.type === 'application/pdf') {
                    // 处理PDF
                    await processPDF(file);
                } else {
                    throw new Error('不支持的文件格式');
                }
            } catch (error) {
                statusElement.textContent = `错误: ${error.message}`;
                console.error(error);
            } finally {
                loadingElement.style.display = 'none';
            }
        }

        // 处理图片
        async function processImage(file) {
            // 显示预览
            const imageUrl = URL.createObjectURL(file);
            previewImage.src = imageUrl;
            previewImage.style.display = 'block';
            
            progressStatus.textContent = '正在进行OCR识别...';
            
            // 使用Tesseract.js进行OCR识别
            const result = await Tesseract.recognize(
                imageUrl,
                'chi_sim+eng',
                {
                    logger: message => {
                        if (message.status === 'recognizing text') {
                            progressStatus.textContent = `识别中: ${Math.round(message.progress * 100)}%`;
                        }
                    }
                }
            );
            
            recognizedText = result.data.text;
            displayRecognizedText();
        }
        
        // 解析网页内容
        async function parseWebContent() {
            const url = document.getElementById('urlInput').value.trim();
            if (!url) {
                alert('请输入有效的网址');
                return;
            }
            
            // 重置状态
            recognizedText = '';
            resultText.textContent = '';
            readButton.disabled = true;
            pauseButton.disabled = true;
            shareButton.disabled = true;
            previewImage.style.display = 'none';
            
            // 显示加载状态
            loadingElement.style.display = 'block';
            progressStatus.textContent = '正在获取网页内容...';
            
            try {
                // 使用CORS代理来解决跨域问题
                const proxyUrl = `https://api.allorigins.win/get?url=${encodeURIComponent(url)}`;
                const response = await fetch(proxyUrl);
                const data = await response.json();
                
                if (data && data.contents) {
                    // 创建一个临时的DOM元素来解析HTML
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(data.contents, 'text/html');
                    
                    // 提取网页中的文本内容
                    // 移除脚本和样式标签
                    const scripts = doc.querySelectorAll('script, style');
                    scripts.forEach(script => script.remove());
                    
                    // 获取正文内容
                    const body = doc.body;
                    
                    // 尝试找到主要内容区域
                    const mainContent = 
                        doc.querySelector('main') || 
                        doc.querySelector('article') || 
                        doc.querySelector('.content') || 
                        doc.querySelector('#content') || 
                        body;
                    
                    // 提取文本，保留段落结构
                    let extractedText = '';
                    const paragraphs = mainContent.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li');
                    
                    if (paragraphs.length > 0) {
                        paragraphs.forEach(p => {
                            const text = p.textContent.trim();
                            if (text) {
                                extractedText += text + '\n\n';
                            }
                        });
                    } else {
                        // 如果没有找到段落标签，则获取所有文本
                        extractedText = mainContent.textContent.trim()
                            .replace(/\\s+/g, ' ')
                            .replace(/\\n+/g, '\n\n');
                    }
                    
                    recognizedText = extractedText || '无法提取网页内容，请尝试其他网址。';
                    
                    // 尝试获取网页标题作为预览
                    const title = doc.querySelector('title');
                    if (title) {
                        statusElement.textContent = `已解析网页: ${title.textContent}`;
                    }
                } else {
                    recognizedText = '无法获取网页内容，请检查URL是否正确。';
                }
                
                displayRecognizedText();
            } catch (error) {
                statusElement.textContent = `错误: ${error.message}`;
                resultText.textContent = '解析网页时出错，请尝试其他网址。';
                console.error(error);
            } finally {
                loadingElement.style.display = 'none';
            }
        }

        // 处理PDF
        async function processPDF(file) {
            const arrayBuffer = await file.arrayBuffer();
            const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
            
            progressStatus.textContent = `正在处理PDF (共${pdf.numPages}页)...`;
            
            let fullText = '';
            
            // 处理每一页
            for (let i = 1; i <= pdf.numPages; i++) {
                progressStatus.textContent = `正在处理第 ${i}/${pdf.numPages} 页...`;
                
                const page = await pdf.getPage(i);
                const viewport = page.getViewport({ scale: 1.5 });
                
                // 创建canvas用于渲染PDF页面
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;
                
                // 渲染PDF页面到canvas
                await page.render({
                    canvasContext: context,
                    viewport: viewport
                }).promise;
                
                // 如果是第一页，显示预览
                if (i === 1) {
                    previewImage.src = canvas.toDataURL();
                    previewImage.style.display = 'block';
                }
                
                // 使用Tesseract.js识别文本
                progressStatus.textContent = `正在识别第 ${i}/${pdf.numPages} 页...`;
                const result = await Tesseract.recognize(
                    canvas,
                    'chi_sim+eng',
                    {
                        logger: message => {
                            if (message.status === 'recognizing text') {
                                progressStatus.textContent = `识别第 ${i}/${pdf.numPages} 页: ${Math.round(message.progress * 100)}%`;
                            }
                        }
                    }
                );
                
                fullText += result.data.text + '\n\n';
            }
            
            recognizedText = fullText;
            displayRecognizedText();
        }

        // 显示识别的文本
        function displayRecognizedText() {
            if (recognizedText.trim() === '') {
                resultText.textContent = '未能识别出文本，请尝试上传清晰的图片或PDF。';
                statusElement.textContent = '识别失败';
                return;
            }
            
            resultText.textContent = recognizedText;
            readButton.disabled = false;
            shareButton.disabled = false;
            statusElement.textContent = '识别完成';
        }

        // 更新字体大小
        function updateFontSize() {
            const size = fontSizeSlider.value;
            fontSizeValue.textContent = `${size}px`;
            resultText.style.fontSize = `${size}px`;
        }

        // 更新对比度
        function updateContrast() {
            const contrast = contrastSelect.value;
            switch (contrast) {
                case 'normal':
                    resultText.style.backgroundColor = '#fff';
                    resultText.style.color = '#333';
                    break;
                case 'high':
                    resultText.style.backgroundColor = '#000';
                    resultText.style.color = '#fff';
                    break;
                case 'yellow':
                    resultText.style.backgroundColor = '#ffff00';
                    resultText.style.color = '#000';
                    break;
            }
        }

        // 开始朗读
        function startReading() {
            if ('speechSynthesis' in window) {
                // 如果已经在朗读，先停止
                if (isReading) {
                    window.speechSynthesis.cancel();
                }
                
                utterance = new SpeechSynthesisUtterance(recognizedText);
                utterance.lang = 'zh-CN';
                
                // 朗读结束事件
                utterance.onend = function() {
                    isReading = false;
                    readButton.textContent = '朗读文本';
                    pauseButton.disabled = true;
                };
                
                window.speechSynthesis.speak(utterance);
                isReading = true;
                readButton.textContent = '停止朗读';
                pauseButton.disabled = false;
                pauseButton.textContent = '暂停朗读';
                statusElement.textContent = '正在朗读...';
            } else {
                alert('您的浏览器不支持语音合成API');
                statusElement.textContent = '浏览器不支持语音合成';
            }
        }

        // 暂停/继续朗读
        function togglePauseReading() {
            if (!isReading) return;
            
            if (window.speechSynthesis.paused) {
                window.speechSynthesis.resume();
                pauseButton.textContent = '暂停朗读';
                statusElement.textContent = '正在朗读...';
            } else {
                window.speechSynthesis.pause();
                pauseButton.textContent = '继续朗读';
                statusElement.textContent = '朗读已暂停';
            }
        }

        // 分享功能
        function shareContent() {
            if (!recognizedText) return;
            
            // 创建分享链接
            const shareText = encodeURIComponent(recognizedText);
            const shareUrl = `data:text/html;charset=utf-8,
                <html>
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>无障碍阅读内容</title>
                    <style>
                        body { font-size: 24px; line-height: 1.6; padding: 20px; max-width: 800px; margin: 0 auto; }
                        .controls { margin-bottom: 20px; }
                        button { padding: 10px 15px; margin-right: 10px; cursor: pointer; }
                    </style>
                </head>
                <body>
                    <div class="controls">
                        <button onclick="speak()">朗读文本</button>
                        <button onclick="toggleSize()">切换字体大小</button>
                        <button onclick="toggleContrast()">切换对比度</button>
                    </div>
                    <div id="content">${recognizedText.replace(/\n/g, '<br>')}</div>
                    <script>
                        let isLarge = true;
                        let contrastMode = 0;
                        
                        function speak() {
                            if ('speechSynthesis' in window) {
                                const text = document.getElementById('content').textContent;
                                const utterance = new SpeechSynthesisUtterance(text);
                                utterance.lang = 'zh-CN';
                                window.speechSynthesis.speak(utterance);
                            } else {
                                alert('您的浏览器不支持语音合成');
                            }
                        }
                        
                        function toggleSize() {
                            const content = document.getElementById('content');
                            content.style.fontSize = isLarge ? '18px' : '32px';
                            isLarge = !isLarge;
                        }
                        
                        function toggleContrast() {
                            const body = document.body;
                            contrastMode = (contrastMode + 1) % 3;
                            
                            switch(contrastMode) {
                                case 0: // 正常
                                    body.style.backgroundColor = '#fff';
                                    body.style.color = '#000';
                                    break;
                                case 1: // 高对比度
                                    body.style.backgroundColor = '#000';
                                    body.style.color = '#fff';
                                    break;
                                case 2: // 黄底黑字
                                    body.style.backgroundColor = '#ffff00';
                                    body.style.color = '#000';
                                    break;
                            }
                        }
                    </script>
                </body>
                </html>
            `;
            
            // 创建并点击链接以打开新窗口
            const a = document.createElement('a');
            a.href = shareUrl;
            a.target = '_blank';
            a.click();
            
            statusElement.textContent = '已创建分享链接';
        }

        // 初始化设置
        updateFontSize();
        updateContrast();
    </script>
</body>
</html>